<template>
  <view class="container">
    <!-- 基本信息模块 -->
    <view class="section-card">
      <view class="section-header">
        <image class="section-icon" src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/10/风车_20251010084002A010.png"></image>
        <text class="section-title">{{ isEditMode ? '编辑' : '新增' }}活动</text>
      </view>

      <view class="form-item">
        <text class="form-label required">活动名称</text>
        <input v-model="spForm.name" class="form-input" placeholder="请填写活动名称" />
      </view>

      <view class="form-item">
        <text class="form-label required">商品说明</text>
        <view class="editor-wrapper">
          <Rboy-editor ref="RboyEditor" @uploadFile="uploadFile" :count="6"></Rboy-editor>
        </view>
      </view>

      <view class="form-item">
        <text class="form-label required">活动照片</text>
        <view class="upload-wrapper">
          <u-upload :fileList="fileList" @afterRead="afterRead" height="200" width="200" @delete="deletePic" name="3" :maxCount="10" :previewFullImage="true">
            <view class="upload-placeholder">
              <u-icon name="plus" size="28" color="#999"></u-icon>
              <text class="upload-text">上传图片</text>
            </view>
          </u-upload>
        </view>
      </view>
    </view>

    <!-- 详细信息模块 -->
    <view class="section-card">
      <view class="section-header">
        <image class="section-icon" src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/10/风车_20251010084002A010.png"></image>
        <text class="section-title">详细信息</text>
      </view>

      <view class="form-item">
        <text class="form-label required">活动时间</text>
        <view class="date-range">
          <u-cell size="large" title="开始时间" :value="spForm.startTime || '请选择'" @click="getTypeStart" isLink hover-class="cell-hover"> </u-cell>
          <u-cell size="large" title="结束时间" :value="spForm.endTime || '请选择'" @click="getTypeEnd" isLink :disabled="!spForm.startTime" hover-class="cell-hover"> </u-cell>
        </view>
      </view>

      <view class="form-item">
        <text class="form-label required">是否上架活动</text>
        <u-cell size="large" :value="typeValue" @click="getTypelx" isLink hover-class="cell-hover"> </u-cell>
      </view>

      <view class="form-item">
        <text class="form-label required">活动排序</text>
        <input v-model.number="spForm.activeOrder" class="form-input" type="number" placeholder="请输入排序值（数字越大越靠前）" />
      </view>
      <view class="form-item">
        <text class="form-label required">建议零售价</text>
        <input v-model="spForm.price" type="digit" class="form-input" placeholder="请输入" />
      </view>
      <view class="form-item" v-show="merInfo.isVendor == 1">
        <text class="form-label required">成本价</text>
        <input v-model="spForm.costPrice" class="form-input" type="digit" placeholder="请输入" />
        <view class="ratio-description" v-if="spForm.price && spForm.costPrice"> 预估分账比例为：{{ ((spForm.costPrice / spForm.price) * 100).toFixed(2) }}% </view>
      </view>
      <view class="form-item">
        <text v-if="merInfo.isVendor == 1" class="form-label required">商户代销金额(陈列费用)</text>
        <text v-else class="form-label required">商户分账金额</text>
        <input v-model="spForm.lsSplittingCollections" class="form-input" type="digit" placeholder="请输入商户代销金额" />
        <view class="ratio-description" v-if="spForm.price && spForm.lsSplittingCollections">
          预估商户分账比例为：{{ ((spForm.lsSplittingCollections / spForm.price) * 100).toFixed(2) }}%
        </view>
      </view>
      <view class="form-item">
        <text class="form-label required">软件服务费</text>
        <input disabled="disabledPlatformSplit" v-model="spForm.lsSplittingPlatforms" class="form-input" type="digit" placeholder="请输入平台分账比例" />
        <view class="ratio-description" v-if="spForm.price && spForm.lsSplittingPlatforms">
          平台分账金额：{{ ((spForm.lsSplittingPlatforms / spForm.price) * 100).toFixed(2) }}%
        </view>
      </view>
      <view class="form-item">
        <text class="form-label required">推广佣金</text>
        <input v-model="promotionCommissions" @input="awffadge" class="form-input" type="digit" placeholder="请输入佣金比例（如：0.1表示10%）" />
        <view class="ratio-description" v-if="spForm.price && promotionCommissions"> 预估佣金分账比例：{{ promotionCommissionsbl }} % </view>
      </view>
      <view class="form-item">
        <text class="form-label required">会员返利</text>
        <input v-model="memberReturnbls" class="form-input" type="digit" placeholder="请输入" />
        <view class="ratio-description" v-if="spForm.price && memberReturnbls"> 会员返利分账比例：{{ spForm.memberReturnbls }} % </view>
      </view>

      <!-- <view class="form-item">
        <text class="form-label required">活动固定收款号</text>
        <input v-model="spForm.subPayNoWater" class="form-input" placeholder="请输入收款号" />
      </view>

      <view class="form-item" v-if="merInfo.isVendor == 1">
        <text class="form-label required">供应商分账比例</text>
        <input v-model="spForm.lsSplittingWater" class="form-input" type="digit" placeholder="请输入供应商分账比例" />
        <view class="ratio-description" v-if="spForm.price && spForm.lsSplittingWater"> 供应商分账金额：{{ (spForm.price * spForm.lsSplittingWater).toFixed(2) }}元 </view>
      </view> -->

      <!--      <view class="form-item">
        <text class="form-label required">商户分账比例</text>
        <input v-model="spForm.lsSplittingCollection" class="form-input" type="digit" placeholder="请输入商户分账比例" />
        <view class="ratio-description" v-if="spForm.price && spForm.lsSplittingCollection"> 商户分账金额：{{ (spForm.price * spForm.lsSplittingCollection).toFixed(2) }}元 </view>
      </view> -->

      <!--    <view class="form-item">
        <text class="form-label required">平台分账比例</text>
        <input disabled="disabledPlatformSplit" v-model="spForm.lsSplittingPlatform" class="form-input" type="digit" placeholder="请输入平台分账比例" />
        <view class="ratio-description" v-if="spForm.price && spForm.lsSplittingPlatform"> 平台分账金额：{{ (spForm.price * spForm.lsSplittingPlatform).toFixed(2) }}元 </view>
      </view> -->

      <view class="form-item" v-if="spForm.price && (spForm.lsSplittingWater || spForm.lsSplittingCollection || spForm.lsSplittingPlatform || spForm.promotionCommissions)">
        <view class="total-ratio-info">
          <view class="ratio-description">
            <!--  总分账比例：{{
              (
                (parseFloat(spForm.lsSplittingWater) || 0) +
                (parseFloat(spForm.lsSplittingCollection) || 0) +
                (parseFloat(spForm.lsSplittingPlatform) || 0) +
                (parseFloat(spForm.promotionCommissions) || 0)
              ).toFixed(2)
            }} -->
            注:此价格为未配置折扣到账的估计金额
          </view>
          <view class="ratio-description">
            <!--   总分账金额：{{
              (
                (parseFloat(spForm.lsSplittingWater) || 0) * spForm.price +
                (parseFloat(spForm.lsSplittingCollection) || 0) * spForm.price +
                (parseFloat(spForm.lsSplittingPlatform) || 0) * spForm.price +
                (parseFloat(spForm.promotionCommissions) || 0) * spForm.price
              ).toFixed(2)
            }}元 -->
          </view>
        </view>
      </view>

      <!--      <view class="form-item">
        <text class="form-label required">水卡活动</text>
        <u-radio-group placement="row" v-model="spForm.isWatercard">
          <u-radio size="30" iconSize="20" labelSize="30" v-for="(item, index) in radiolist1" :key="index" :label="item.name" :name="item.label"> </u-radio>
        </u-radio-group>
      </view> -->
    </view>

    <!-- 供应商模块 -->
    <view class="section-card" v-if="merInfo.isVendor == 1">
      <view class="section-header">
        <image class="section-icon" src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/10/风车_20251010084002A010.png"></image>
        <text class="section-title">供应商模块</text>
      </view>

      <view class="form-item">
        <text class="form-label">选择推广商户</text>
        <view @click="openMerchantSelector" class="merchant-selector">
          <view v-if="selectedMerchants.length === 0" class="placeholder-text"> 请选择推广商户 </view>
          <view v-else class="selected-merchants">
            <u-tag v-for="(merchant, index) in selectedMerchants" :key="index" :text="merchant.merName" type="primary" size="mini" closable @close="removeMerchant(index)" />
          </view>
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="button-container">
      <u-button type="primary" @click="addOwner" :loading="saving">保存</u-button>
    </view>

    <!-- 商户选择弹窗 -->
    <u-popup :show="showMerchantSelector" mode="bottom" @close="closeMerchantSelector" round>
      <view class="merchant-selector-popup">
        <view class="popup-header">
          <text class="popup-title">选择推广商户</text>
          <u-icon name="close" @click="closeMerchantSelector" size="40"> </u-icon>
        </view>

        <view class="search-box">
          <u-search v-model="merchantSearchKeyword" placeholder="搜索商户名称" height="60rpx" :showAction="false" @search="searchMerchants" @clear="searchMerchants"> </u-search>
        </view>

        <scroll-view class="merchant-list" scroll-y @scrolltolower="loadMoreMerchants" :refresher-enabled="true" :refresher-triggered="refreshing" @refresherrefresh="onRefresh">
          <u-checkbox-group v-model="selectedMerchantId" @change="awdwafwadwacs">
            <u-cell-group>
              <u-cell v-for="(merchant, index) in merchants" :key="merchant.id" :title="merchant.merName" :label="merchant.merAddress || '暂无地址'">
                <template #right-icon>
                  <u-checkbox size="30" :name="merchant.id" shape="circle"> </u-checkbox>
                </template>
              </u-cell>
            </u-cell-group>
          </u-checkbox-group>

          <u-loadmore :status="loadStatus" :line="true" v-if="merchants.length > 0" />

          <view v-if="merchants.length === 0 && !loading" class="no-data">
            <u-empty mode="list" text="暂无商户数据"> </u-empty>
          </view>
        </scroll-view>

        <view class="popup-footer">
          <view class="footer-buttons">
            <u-button type="default" size="small" @click="closeMerchantSelector" style="margin-right: 10px"> 关闭 </u-button>
            <u-button type="primary" size="small" @click="confirmSelection"> 确定 </u-button>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 日期选择器 -->
    <u-calendar :show="showStart" :mode="mode" rowHeight="150" @confirm="confirmStart" @close="showStart = false" :maxDate="calendar.maxDate" :monthNum="calendar.monthNum">
    </u-calendar>

    <u-calendar :show="showEnd" :mode="mode" rowHeight="150" @confirm="confirmEnd" @close="showEnd = false" :maxDate="calendar.maxDate" :monthNum="calendar.monthNum"> </u-calendar>

    <!-- 类型选择器 -->
    <u-picker :show="showType" @cancel="showType = false" :columns="columns" keyName="categoryName" @confirm="getTsType"> </u-picker>
  </view>
</template>

<script>
import RboyEditor from '../../components/Rboy-editor/Rboy-editor.vue';
import { categorylist, addOrUpdateReId, merlist, activityById, getUserInfo } from '../../utils/request_sh.js';

export default {
  components: {
    RboyEditor
  },
  data() {
    return {
      isEditMode: false,
      activityId: null,
      pageNum: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      refreshing: false,
      loadStatus: 'loadmore',
      merchantSearchKeyword: '',
      saving: false,
      showMerchantSelector: false,
      merchants: [],
      selectedMerchantId: '', // 单选ID
      selectedMerchants: [], // 已选商户列表

      radiolist1: [
        { name: '是', label: 0 },
        { name: '否', label: 1 }
      ],

      calendar: {
        minDate: '',
        maxDate: '',
        defaultDate: '',
        monthNum: 36
      },
      // shengyujine: 0,
      showType: false,
      columns: [],
      showStart: false,
      showEnd: false,
      mode: 'single',
      fileList: [], // 用于u-upload组件显示已上传的文件
      typeValue: '请选择',

      spForm: {
        icon: '',
        showInfo: '',
        name: '',
        illustrate: '',
        activeOrder: 1,
        startTime: '',
        endTime: '',
        ebMerId: '',
        vouchers: [],
        costPrice: 0,
        isLaundry: 1,
        isWatercard: 1,
        promotionCommissions: '',
        status: '',
        /*    subPayNoWater: '', */
        lsSplittingWater: '',
        lsSplittingCollection: '',
        lsSplittingPlatform: '',
        lsSplittingPlatforms: 0,
        memberReturnbl: '',
        price: '', // 添加price字段
        disabledPlatformSplit: false,
        lsSplittingCollections: 0
      },
      promotionCommissionsbl: 0,
      promotionCommissions: 0,
      memberReturnbls: 0,
      merInfo: {},
      images: '',
      fileName: ''
    };
  },
  computed: {
    shengyujine() {
      var d =
        parseFloat(this.spForm.price) - (parseFloat(this.spForm.costPrice) + parseFloat(this.spForm.lsSplittingPlatforms) + parseFloat(this.spForm.lsSplittingCollections)) || 0;
      return d.toFixed(2);
    }
    // promotionCommissions: {
    //   get() {
    // // console.log(this.memberReturnbls)
    // // if(this.memberReturnbls == 0) {
    // var d =
    //   parseFloat(this.spForm.price) - (parseFloat(this.spForm.costPrice) + parseFloat(this.spForm.lsSplittingPlatforms) + parseFloat(this.spForm.lsSplittingCollections) + parseFloat(this.memberReturnbls) ) || 0;
    // // this.ffawdqfwe = d.toFixed(2)
    // this.promotionCommissionsbl = ((d / this.spForm.price) * 100).toFixed(2);
    // this.memberReturnbls = parseFloat(this.shengyujine) - parseFloat(d);
    // return d.toFixed(2);
    // // } else {
    // //  var d =
    // //    parseFloat(this.spForm.price) - (parseFloat(this.spForm.costPrice) + parseFloat(this.spForm.lsSplittingPlatforms) + parseFloat(this.spForm.lsSplittingCollections) + parseFloat(this.memberReturnbls)) || 0;
    // //  this.promotionCommissionsbl = ((d / this.spForm.price) * 100).toFixed(2);
    // //  return d.toFixed(2);
    // // }

    //   }
    //   // set(val) {
    //   // 	this.promotionCommissionsbl = ((val / this.spForm.price) * 100).toFixed(2);
    //   // 	this.promotionCommissions = val
    //   // }
    // }
    // 'spForm.promotionCommissions'() {
    //   return ((this.promotionCommissions / this.spForm.price) * 100).toFixed(2);
    // }
  },

  watch: {
    promotionCommissions() {
      this.promotionCommissionsbl = ((this.promotionCommissions / this.spForm.price) * 100).toFixed(2);
    },
    memberReturnbls(val) {
      this.spForm.memberReturnbls = ((this.memberReturnbls / this.spForm.price) * 100).toFixed(2);
    },
    // ffawdqfwe() {
    //   this.spForm.promotionCommissions = ((parseFloat(this.ffawdqfwe) / this.spForm.price) * 100).toFixed(2);
    // },
    // promotionCommissions() {

    // },
    'spForm.price'() {
      this.spForm.lsSplittingPlatforms = (this.spForm.price * this.spForm.lsSplittingPlatform).toFixed(2);
    }
  },
  onLoad(option) {
    this.merInfo = uni.getStorageSync('userInfo');
    const merId = this.merInfo.merId;
    getUserInfo(merId).then((res) => {
      uni.setStorageSync('shUserInfo', res.data);
      this.merName = res.data;
      if (this.merInfo.activityPlatformCommissionbl) {
        this.spForm.lsSplittingPlatform = this.merInfo.activityPlatformCommissionbl;
        this.disabledPlatformSplit = true;
      }
    });

    if (option.id) {
      this.isEditMode = true;
      this.activityId = option.id;
      this.getSpInfo(option.id);
    }

    this.chooseTimed();
  },

  methods: {
    awdwafwadwacs(val) {
      this.merchants.forEach((item) => {
        val.forEach((itemsda) => {
          if (item.id == itemsda) {
            this.selectedMerchants.push(item);
          }
        });
      });
      const uniqueArr = this.selectedMerchants.filter((item, index, self) => {
        return index === self.findIndex((obj) => obj.id == item.id);
      });
      this.selectedMerchants = uniqueArr;
      console.log(val);
    },
    awffadge(code) {
      console.log(code.detail.value);
      this.ffawdqfwe = code.detail.value;
      if (code.detail.value) {
        var d = parseFloat(this.shengyujine) - parseFloat(code.detail.value) || 0;
        console.log(d);
        this.memberReturnbls = d >= 0 ? d.toFixed(2) : 0;
      } else {
        this.memberReturnbls = parseFloat(this.shengyujine);
      }
      // this.spForm.memberReturnbls = ((this.memberReturnbls / this.spForm.price) * 100).toFixed(2);
      this.promotionCommissionsbl = ((parseFloat(code.detail.value) / this.spForm.price) * 100).toFixed(2);

      // this.$set(this.spForm, 'promotionCommissions', ((parseFloat(code.detail.value) / this.spForm.price) * 100).toFixed(2))
    },
    openMerchantSelector() {
      this.showMerchantSelector = true;
      // 单选模式下，如果已有选择，则设置为第一个
      if (this.selectedMerchants.length > 0) {
        this.selectedMerchantId = this.selectedMerchants[0].id;
      } else {
        this.selectedMerchantId = '';
      }

      if (this.merchants.length === 0) {
        this.loadMerchants();
      }
    },

    closeMerchantSelector() {
      this.showMerchantSelector = false;
    },

    confirmSelection() {
      // 根据选中的ID找到对应的商户信息
      // const selectedMerchant = this.merchants.find((merchant) => merchant.id === this.selectedMerchantId);
      // if (selectedMerchant) {
      //   this.selectedMerchants = [selectedMerchant];
      //   this.spForm.subPayNoWater = selectedMerchant.subPayNo;
      //   console.log('🚀 ~  this.spForm.subPayNoWater:', this.spForm.subPayNoWater);
      // } else {
      //   this.selectedMerchants = [];
      //   this.spForm.subPayNoWater = '';
      // }
      this.closeMerchantSelector();
    },

    resetSelection() {
      this.selectedMerchantId = '';
    },

    removeMerchant(index) {
      this.selectedMerchants.splice(index, 1);
      this.selectedMerchantId = '';
    },

    async loadMerchants() {
      if (this.loading) return;

      this.loading = true;
      this.loadStatus = 'loading';

      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        };

        if (this.merchantSearchKeyword) {
          params.merName = this.merchantSearchKeyword;
        }

        const res = await merlist(params);
        const newList = res.rows || [];
        this.total = res.total || 0;

        if (this.pageNum === 1) {
          this.merchants = newList;
        } else {
          this.merchants = [...this.merchants, ...newList];
        }

        if (this.merchants.length >= this.total) {
          this.loadStatus = 'nomore';
        } else {
          this.loadStatus = 'loadmore';
        }
      } catch (error) {
        uni.showToast({
          title: '获取商户列表失败',
          icon: 'none'
        });
        this.loadStatus = 'loadmore';
      } finally {
        this.loading = false;
        this.refreshing = false;
      }
    },

    searchMerchants() {
      this.pageNum = 1;
      this.loadMerchants();
    },

    onRefresh() {
      this.refreshing = true;
      this.pageNum = 1;
      this.loadMerchants();
    },

    loadMoreMerchants() {
      if (this.loadStatus !== 'nomore' && !this.loading) {
        this.pageNum++;
        this.loadMerchants();
      }
    },

    async set_content() {
      if (this.$refs.RboyEditor && this.spForm.showInfo) {
        this.$refs.RboyEditor.editor_setContents(this.spForm.showInfo);
      }
    },

    async get_content() {
      if (this.$refs.RboyEditor) {
        this.spForm.showInfo = await this.$refs.RboyEditor.editor_getcontents();
      }
    },

    async uploadFile(event) {
      for (let item in event.tempFilePaths) {
        let src = await this.uploadFilePromise(event.tempFilePaths[item]);
        this.$refs.RboyEditor.editor_insertImage({
          src: 'https://www.wantongkonggu.cn/' + src.fileName,
          alt: '图像'
        });
      }
    },

    chooseTimed() {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (month <= 9) month = '0' + month;
      if (day <= 9) day = '0' + day;

      let minyear = year - 2;
      let maxyear = year + 2;

      this.calendar.minDate = minyear + '-' + month + '-' + day;
      this.calendar.maxDate = maxyear + '-' + month + '-' + day;
      this.calendar.defaultDate = year + '-' + month + '-' + day;
    },

    confirmStart(time) {
      this.spForm.startTime = time[0];
      this.showStart = false;
    },

    confirmEnd(time) {
      if (this.spForm.startTime && Date.parse(new Date(this.spForm.startTime)) > Date.parse(new Date(time[0]))) {
        uni.showToast({
          icon: 'none',
          title: '结束时间不能早于开始时间！'
        });
        return;
      }
      this.spForm.endTime = time[0];
      this.showEnd = false;
    },

    getSpInfo(id) {
      activityById(id).then((res) => {
        if (res.code === 200) {
          this.spForm = { ...this.spForm, ...res.data };
          this.typeValue = res.data.status == 0 ? '是' : '否';
          if (this.merInfo.activityPlatformCommissionbl) {
            this.spForm.lsSplittingPlatform = this.merInfo.activityPlatformCommissionbl;
            this.disabledPlatformSplit = true;
          }
          // 处理活动照片回显
          this.spForm.price = res.data.msrp;
          this.spForm.lsSplittingPlatforms = (this.spForm.price * res.data.lsSplittingPlatform).toFixed(2); /* 平台分账比例 */
          this.spForm.lsSplittingCollections = (this.spForm.price * res.data.lsSplittingCollection).toFixed(2); /* 商户分账比例 */
          this.promotionCommissionsbl = res.data.promotionCommissions * 100;
          this.promotionCommissions = (parseFloat(this.spForm.price) * parseFloat(res.data.promotionCommissions)).toFixed(2);
          setTimeout(() => {
            this.spForm.memberReturnbls = res.data.memberReturnbl * 100;
            this.memberReturnbls = (this.spForm.price * res.data.memberReturnbl).toFixed(2);
          }, 500);
          if (res.data.icon) {
            this.images = 'https://www.wantongkonggu.cn/' + res.data.icon;
            this.fileName = res.data.icon;

            // 更新fileList以在u-upload中显示图片
            this.fileList = [
              {
                url: this.images,
                fileName: this.fileName
              }
            ];
          }

          if (res.data.pushEbMerObjectLs && Array.isArray(res.data.pushEbMerObjectLs)) {
            this.selectedMerchants = res.data.pushEbMerObjectLs.map((merchant) => ({
              id: merchant.id,
              merName: merchant.merName,
              subPayNo: merchant.subPayNo
            }));
            // 单选模式下设置选中ID
            if (this.selectedMerchants.length > 0) {
              this.selectedMerchantId = this.selectedMerchants[0].id;
            }
          }

          this.$nextTick(() => {
            setTimeout(() => {
              this.set_content();
            }, 1000);
          });
        }
      });
    },

    getTypeStart() {
      this.showStart = true;
    },

    getTypeEnd() {
      if (!this.spForm.startTime) {
        uni.showToast({
          icon: 'none',
          title: '请先选择开始时间'
        });
        return;
      }
      this.showEnd = true;
    },

    getTsType({ value }) {
      this.showType = false;
      if (this.isType == 1) {
        this.typeValue = value[0].categoryName;
        this.stasus = value[0].merchantCategoryId;
      }
    },

    getTypelx() {
      this.isType = 1;
      this.showType = true;
      this.columns = [
        [
          { categoryName: '是', merchantCategoryId: '0' },
          { categoryName: '否', merchantCategoryId: '1' }
        ]
      ];
    },

    deletePic(event) {
      this.fileList.splice(event.index, 1);
      // 如果fileList为空，清除fileName
      if (this.fileList.length === 0) {
        this.fileName = '';
      }
    },

    async afterRead(event) {
      try {
        const result = await this.uploadFilePromise(event.file.url);
        this.images = 'https://www.wantongkonggu.cn/' + result.fileName;
        this.fileName = result.fileName;

        // 更新fileList以支持预览
        this.fileList.push({
          url: this.images,
          fileName: result.fileName
        });
      } catch (err) {
        uni.showToast({
          icon: 'none',
          title: '图片上传失败'
        });
      }
    },

    uploadFilePromise(url) {
      const userInfo = uni.getStorageSync('userInfo');
      const token = userInfo ? userInfo.token : '';

      return new Promise((resolve, reject) => {
        uni.uploadFile({
          header: {
            Authorization: token
          },
          url: 'https://www.wantongkonggu.cn/api/adminApph7/common/upload',
          filePath: url,
          name: 'file',
          formData: {
            user: 'test'
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data);
              resolve(data);
            } catch (e) {
              reject(e);
            }
          },
          fail: reject
        });
      });
    },

    validateForm() {
      this.spForm.msrp = this.spForm.price;
      // 成本
      this.spForm.lsSplittingWater = (this.spForm.costPrice / this.spForm.price).toFixed(4);
      // 商户
      this.spForm.lsSplittingCollection = (this.spForm.lsSplittingCollections / this.spForm.price).toFixed(4);
      // 平台
      this.spForm.lsSplittingPlatform = (this.spForm.lsSplittingPlatforms / this.spForm.price).toFixed(4);
      this.spForm.promotionCommissions = (this.promotionCommissionsbl / 100).toFixed(4);
      this.spForm.memberReturnbl = (this.spForm.memberReturnbls / 100).toFixed(2);
      console.log(this.spForm.lsSplittingWater);
      console.log(this.spForm.lsSplittingCollection);
      console.log(this.spForm.lsSplittingPlatform);
      console.log(this.spForm.promotionCommissions);
      console.log(this.spForm.memberReturnbl);
      if (!this.spForm.name) {
        uni.showToast({ icon: 'none', title: '请输入活动名称' });
        return false;
      }

      if (!this.fileName) {
        uni.showToast({ icon: 'none', title: '请上传活动照片' });
        return false;
      }

      if (!this.spForm.startTime || !this.spForm.endTime) {
        uni.showToast({ icon: 'none', title: '请选择活动时间' });
        return false;
      }

      if (this.spForm.activeOrder === '' || this.spForm.activeOrder === null) {
        uni.showToast({ icon: 'none', title: '请输入活动排序' });
        return false;
      }

      /*       if (!this.spForm.promotionCommissions) {
        uni.showToast({ icon: 'none', title: '请输入佣金比例' });
        return false;
      } */

      /*       if (!this.spForm.subPayNoWater) {
        uni.showToast({ icon: 'none', title: '请选择推广商户' });
        return false;
      } */

      const waterSplit = parseFloat(this.spForm.lsSplittingWater) || 0;
      const collectionSplit = parseFloat(this.spForm.lsSplittingCollection) || 0;
      const platformSplit = parseFloat(this.spForm.lsSplittingPlatform) || 0;
      const commissionSplit = parseFloat(this.spForm.promotionCommissions) || 0;
      const memberReturnbl = parseFloat(this.spForm.memberReturnbl) || 0;
      // if (waterSplit < 0 || waterSplit > 1) {
      //   uni.showToast({ icon: 'none', title: '供应商分账比例应在0-1之间' });
      //   return false;
      // }

      // if (collectionSplit < 0 || collectionSplit > 1) {
      //   uni.showToast({ icon: 'none', title: '商户分账比例应在0-1之间' });
      //   return false;
      // }

      // if (platformSplit < 0 || platformSplit > 1) {
      //   uni.showToast({ icon: 'none', title: '平台分账比例应在0-1之间' });
      //   return false;
      // }

      // if (commissionSplit < 0 || commissionSplit > 1) {
      //   uni.showToast({ icon: 'none', title: '佣金比例应在0-1之间' });
      //   return false;
      // }
      // if (memberReturnbl < 0 || memberReturnbl > 1) {
      //   uni.showToast({ icon: 'none', title: '会员返利比例应在0-1之间' });
      //   return false;
      // }

      const totalSplit = (
        parseFloat(this.spForm.costPrice) +
        parseFloat(this.spForm.lsSplittingCollections) +
        parseFloat(this.spForm.lsSplittingPlatforms) +
        parseFloat(this.promotionCommissions) +
        parseFloat(this.memberReturnbls)
      ).toFixed(2);
      console.log(parseFloat(this.spForm.costPrice));
      console.log(parseFloat(this.spForm.lsSplittingCollections));
      console.log(parseFloat(this.spForm.lsSplittingPlatforms));
      console.log(parseFloat(this.promotionCommissions));
      console.log(parseFloat(this.memberReturnbls));
      console.log(totalSplit);
      console.log(this.spForm.price);
      if (totalSplit != parseFloat(this.spForm.price).toFixed(2)) {
        uni.showModal({
          title: '提示',
          content: '成本、代销、软件服务、佣金、会员分账金额必须等于零售价',
          success: function (res) {
            /*             if (res.confirm) {
              console.log('用户点击确定');
            } else if (res.cancel) {
              console.log('用户点击取消');
            } */
          }
        });
        return false;
      }

      return true;
    },

    async addOwner() {
      if (this.saving) return;

      if (!this.validateForm()) {
        return;
      }

      this.saving = true;

      try {
        await this.get_content();

        const userInfo = uni.getStorageSync('userInfo') || {};
        this.spForm.icon = this.fileName;
        this.spForm.ebMerId = userInfo.merId;
        this.spForm.status = this.stasus;
        this.spForm.isVendorActivity = this.merInfo.isVendor;

        if (this.isEditMode) {
          this.spForm.id = this.activityId;
        }
        // selectedMerchants
        // 修改这里：单选模式下使用 selectedMerchantId 而不是 selectedMerchantIds
        // this.spForm.pushEbMerIds = this.selectedMerchantId;
        this.spForm.pushEbMerIds = '';
        this.selectedMerchants.forEach((item, index) => {
          if (index == this.selectedMerchants.length - 1) {
            this.spForm.pushEbMerIds += item.id;
          } else {
            this.spForm.pushEbMerIds += item.id + ',';
          }
        });
        const res = await addOrUpdateReId(this.spForm);

        if (res.code === 200) {
          uni.$u.toast('操作成功');

          setTimeout(() => {
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];

            uni.navigateBack({
              delta: 1,
              success: () => {
                if (prevPage && typeof prevPage.onLoad === 'function') {
                  prevPage.onLoad();
                }
              }
            });
          }, 1000);
        } else {
          uni.showToast({
            icon: 'none',
            title: res.msg || '操作失败'
          });
        }
      } catch (error) {
        console.log(error);
        uni.showToast({
          icon: 'none',
          title: '系统错误，请联系管理员处理'
        });
      } finally {
        this.saving = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f6fa;
  min-height: 100vh;
  padding: 20rpx;
}

.section-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.section-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.form-item {
  margin-bottom: 30rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;

  &.required::before {
    content: '* ';
    color: #ff4d4f;
  }
}

.form-input {
  background-color: #f8f9fc;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 2rpx solid #ebedf0;

  &:focus {
    border-color: #2979ff;
  }
}

.date-range {
  border: 2rpx solid #ebedf0;
  border-radius: 12rpx;
  overflow: hidden;
}

.cell-hover {
  background-color: #f8f9fc;
}

.editor-wrapper {
  border: 2rpx solid #ebedf0;
  border-radius: 12rpx;
  overflow: hidden;
}

.upload-wrapper {
  margin-top: 10rpx;
}

.upload-placeholder {
  border: 2rpx dashed #c0c4cc;
  border-radius: 12rpx;
  width: 200rpx;
  height: 200rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.upload-icon {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
}

.merchant-selector {
  background-color: #f8f9fc;
  border-radius: 12rpx;
  padding: 20rpx;
  min-height: 88rpx;
  border: 2rpx solid #ebedf0;
}

.placeholder-text {
  color: #999;
  font-size: 28rpx;
}

.selected-merchants {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.button-container {
  padding: 20rpx 0 40rpx;
}

// 弹窗样式
.merchant-selector-popup {
  height: 80vh;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
}

.search-box {
  padding: 20rpx 30rpx;
  background-color: #f8f8f8;
}

.merchant-list {
  flex: 1;
  height: 0;

  .no-data {
    padding: 40rpx 0;
    text-align: center;
  }
}

.popup-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
}

.selected-info {
  font-size: 28rpx;
  color: #666;
}

.footer-buttons {
  display: flex;
  margin-left: auto;
}

// 添加比例说明样式
.ratio-description {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
}

.total-ratio-info {
  background-color: #f0f8ff;
  border-radius: 8rpx;
  padding: 15rpx;
  margin-top: 15rpx;
}
</style>
